package com.lry;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class Node {

    private Map<String,NodeValue> kvMap;
    private SegmentLock<String> segmentLock;
    private String name;
    public boolean error;

    public Node(String name){
        kvMap = new ConcurrentHashMap<>();
        segmentLock = new SegmentLock();
        this.name = name;
    }

    public NodeValue get(String key){
        return kvMap.get(key);
    }

    public String put(String key,String value){
        if(error){
            log.info("{},put error,key={},value={}",name,key,value);
            return null;
        }
        NodeValue nodeValue = null;
        try{
            segmentLock.lock(key);

            if(kvMap.containsKey(key)){
                nodeValue = kvMap.get(key);
                nodeValue.setValue(value);
                nodeValue.incrVersion();
            }else{
                nodeValue = new NodeValue(value,name);
            }
        }finally {
            segmentLock.unlock(key);
        }

        log.info("{},put,key={},value={}",name,key,nodeValue);
        kvMap.put(key,nodeValue);

        return Resp.OK.getResult();
    }
}
